package com.workstudy.wstudy.service.impl;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/webSocket")
public class WebSocketServiceImpl {

    private Session session;

    private static ConcurrentHashMap<Session, String> webSocketSession = new ConcurrentHashMap<Session, String>();


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("建立连接时session：" + session);
    }

    @OnClose
    public void onClose() {
        webSocketSession.remove(session);
        System.out.println("【websocket消息】链接断开，总数：" + webSocketSession.size());
        System.out.println("有用户下线，现在map:" + webSocketSession);
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端发来的消息：" + message);
        if (message.split(";")[0].equals("userId")) {
            String userId = message.split(";")[1];
            webSocketSession.put(session, userId);
            System.out.println("【websocket消息】有新链接，总数：" + webSocketSession.size());
        }
        System.out.println(webSocketSession);
    }

    public void sendMessage(String userId, String message) {       //给指定人发消息
        for (Session getSession : webSocketSession.keySet()) {
            if (webSocketSession.get(getSession).equals(userId)) {
                System.out.println("发出指定消息，message：" + message);
                try {
                    getSession.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
